﻿using System;
using System.Collections.Generic;

namespace ECommon
{
    /// <summary>
    /// 属性工具
    /// </summary>
    public static class AttributeTool
    {
        /// <summary>
        /// 获取指定的自定义属性
        /// </summary>
        /// <typeparam name="T">自定义属性泛型</typeparam>
        /// <param name="type">携带属性的初始类型</param>
        /// <returns>自定义属性</returns>
        /// <exception cref="ArgumentNullException">参数为空异常</exception>
        /// <exception cref="Exception">计算结果异常</exception>
        public static T GetCustomAttribute<T>(Type type) where T : Attribute
        {
            if (type == null)
            {
                throw new ArgumentNullException("type", "传入参数：type为空");
            }
            object[] attributes = type.GetCustomAttributes(typeof(T), true);
            if (attributes != null && attributes.Length > 0)
            {
                if (attributes[0] != null)
                {
                    return (T)attributes[0];
                }
            }
            throw new Exception("属性的计算结果为空");
        }

        /// <summary>
        /// 获取指定的自定义属性
        /// </summary>
        /// <typeparam name="T">自定义属性泛型</typeparam>
        /// <param name="type">携带属性的初始类型</param>
        /// <returns>自定义属性</returns>
        /// <exception cref="ArgumentNullException">参数为空异常</exception>
        /// <exception cref="Exception">计算结果异常</exception>
        public static List<T> GetCustomAttributes<T>(Type type) where T : Attribute
        {
            if (type == null)
            {
                throw new ArgumentNullException("type", "传入参数：type为空");
            }
            object[] attributes = type.GetCustomAttributes(typeof(T), true);
            List<T> list = new List<T>();
            if (attributes != null && attributes.Length > 0)
            {
                foreach (object attr in attributes)
                {
                    if (attr != null)
                    {
                        list.Add((T)attr);
                    }
                }
            }
            if (list.Count > 0)
            {
                return list;
            }
            else
            {
                throw new Exception("属性的计算结果为空");
            }
        }
    }
}